import axios from 'axios'
import { useUserStore } from '../stores/user'
import { useRouter } from 'vue-router'
import API_BASE_URL from '../config/api'

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 5000
})

const router = useRouter()

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export const auth = {
  login: (data) => api.post('/auth/login', data),
  register: (data) => api.post('/auth/register', data),
  getProfile: () => api.get('/auth/me'),
  updateProfile: (data) => api.put('/auth/me', data),
  uploadAvatar: (file) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return api.post('/auth/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

export const scams = {
  getList: (params) => api.get('/scams', { params }),
  getDetail: (id) => api.get(`/scams/${id}`),
  create: (data) => api.post('/scams', data),
  update: (id, data) => api.put(`/scams/${id}`, data),
  delete: (id) => api.delete(`/scams/${id}`)
}

export const comments = {
  getList: (scamId) => api.get(`/comments/scam/${scamId}`),
  create: (scamId, data) => api.post(`/comments/scam/${scamId}`, data),
  delete: (scamId, commentId) => api.delete(`/comments/${commentId}`)
}

export const admin = {
  getDashboardData: () => api.get('/admin/dashboard'),
  getUsers: (params) => api.get('/admin/users', { params }),
  updateUser: (id, data) => api.put(`/admin/users/${id}`, data),
  deleteUser: (id) => api.delete(`/admin/users/${id}`),
  getScams: (params) => api.get('/admin/scams', { params }),
  verifyScam: (id) => api.put(`/admin/scams/${id}/verify`),
  rejectScam: (id) => api.put(`/admin/scams/${id}/reject`),
  deleteScam: (id) => api.delete(`/admin/scams/${id}`)
}

export default api 